<?php
namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;

class UserController
{
    protected $db;

    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    /**
     * User login view.
     *
     * @return void
     */
    public function login()
    {
        loadView('users/login');
    }

    /**
     * User creation view.
     *
     * @return void
     */
    public function create()
    {
        loadView('users/create');
    }


    /* 
     * Function to store user data
     */
    public function store()
    {
        $name = $_POST['name'];
        $email = $_POST['email'];
        $city = $_POST['city'];
        $province = $_POST['province'];
        $password = $_POST['password'];
        $passwordConfirmation = $_POST['password_confirmation'];
        $errors = [];

        if (!Validation::email($email)) {
            $errors['email'] = 'Invalid email format.';
        }
        if (!Validation::string($name, 2, 50)) {
            $errors['name'] = 'Name must be between 2 and 50 characters.';
        }
        if (!Validation::string($password, 6, 50)) {
            $errors['password'] = 'Password must be between 6 and 50 characters.';
        }
        if (!Validation::match($password, $passwordConfirmation)) {
            $errors['password_confirmation'] = 'Passwords do not match.';
        }
        if (!empty($errors)) {
            // Have errors
            loadView('users/create', [
                'errors' => $errors,
                'user' =>
                    [
                        'name' => $name,
                        'email' => $email,
                        'city' => $city,
                        'province' => $province,
                    ]
            ]);

            exit();

        } else {
            // Check email
            $params = [
                'email' => $email
            ];
            $user = $this->db->query('SELECT * FROM users WHERE email = :email', $params)->fetch();
            if ($user) {
                $errors['email'] = 'Email already exists!';
                loadView('users/create', [
                    'errors' => $errors
                ]);
                exit;
            }

            // Create account
            $params = [
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
                'password' => password_hash($password, PASSWORD_DEFAULT)
            ];

            $this->db->query('INSERT INTO users (name, email, city, province, password) VALUES (:name, :email, :city, :province, :password)', $params);

            // Get new user ID
            $userId = $this->db->conn->lastInsertId();
            Session::set('user', [
                'id' => $userId,
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
            ]);

            redirect('/');
        }
    }

    /**
     * Logout
     * @return void
     */
    public function logout()
    {
        // Clear all session data
        Session::clearAll();
        // Retrieve session cookie parameters
        $params = session_get_cookie_params();
        // Delete the session cookie by setting its expiration to one day ago
        setcookie('PHPSESSID', '', time() - 86400, $params['path'], $params['domain']);
        // Redirect to the home page
        redirect('/');
    }

    /**
     * Verify user credentials
     *@return void 
     */
    public function authenticate()
    {
        // POST variables
        $email = $_POST['email'];
        $password = $_POST['password'];
        $errors = [];
        // Validate email
        if (!Validation::email($email)) {
            $errors['email'] = 'Invalid email format.';
        }
        // Validate password
        if (!Validation::string($password, 6, 50)) {
            $errors['password'] = 'Invalid password format.';
        }
        // If has errors, reload the login view with errors
        if (!empty($errors)) {
            loadView('users/login', ['errors' => $errors]);
            exit;
        }
        // Parameters for authentication
        $params = [
            'email' => $email
            // Other parameters...
        ];

        // Find user
        $user = $this->db->query('SELECT * FROM users WHERE email = :email', $params)->fetch();
        if (!$user) {
            $errors['email'] = 'User not exists or invalid password.';
            loadView('users/login', ['errors' => $errors]);
            exit;
        }
        if (!password_verify($password, $user->password)) {
            $errors['email'] = 'User not exists or invalid password.';
            loadView('users/login', ['errors' => $errors]);
            exit;
        }
        Session::set('user', [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'city' => $user->city,
            'province' => $user->province
        ]);
        redirect('/');
    }


}